import 'package:flutter/material.dart';
import 'package:spring_dict/Entities/DictDirection.dart';
import 'package:spring_dict/Entities/DictItem.dart';
import 'package:spring_dict/Entities/SearchMode.dart';
import 'package:spring_dict/Entities/SearchRequest.dart';
import 'package:spring_dict/Entities/SearchResponse.dart';
import 'package:spring_dict/Events/index.dart';
import 'package:spring_dict/Store/State.dart';
import 'package:spring_dict/UI/Component/ListDividerGenerator.dart';
import 'package:spring_dict/UI/Component/MessageDialog.dart';
import 'package:spring_dict/global.dart';

class SearchPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) => SearchPageStatefull();
}

class SearchPageStatefull extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => SearchPageState();
}

class SearchPageState extends State<SearchPageStatefull> {
  var index = 0;
  var eventIds = [];
  TextEditingController searchController = TextEditingController(text: searchRequest?.keyWord ?? "");


  @override
  void initState() {
    eventIds = [
      globalBus.subscribe<List<DictDirection>>(ON_DIRECTION_UPDATED, (bus, data){setState(() {});}),
      globalBus.subscribe<DictDirection>(ON_DIRECTION_SELECTED, (bus, direction){setState(() {});}),
      globalBus.subscribe<SearchMode>(ON_SEARCH_MODE_SELECTED, (bus, mode){setState(() {});}),
      globalBus.subscribe<SearchResponse>(ON_SEARCH_SUCCESS, (bus, data){setState(() {});}),
    ];

    searchController.addListener((){
      var key = searchController.text;
      if (key == "" || key == searchRequest?.keyWord ?? "") return;
      log("TextEditableController trigger::: key: $key");
      globalBus.publish<SearchRequest>(ON_SEARCH_REQUEST, SearchRequest(
        keyWord: key,
        searchMode: selectedSearchMode
      ));
    });
//    log("InitState", context: this);
    super.initState();
  }

  @override
  void deactivate() {
    eventIds.forEach((id) => globalBus.unSubscribe(id));
    super.deactivate();
  }

  @override
  Widget build(BuildContext context) {
//    log("Build run.", context: this);
    var widgetList = ListDividerGenerator((searchResponse?.items?? []).map((i) => buildItem(context, i)).toList(), Divider()).items;

    return CustomScrollView(
      slivers: <Widget>[
        SliverAppBar(
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.map, color: Colors.white,),
              onPressed: () {
                showModalBottomSheet(context: context, builder: (context) => buildSearchModeBottomSheet(context));
              },
            ),
            Expanded(child: Center(

            )),
            IconButton(
              icon: Icon(Icons.compare_arrows, color: Colors.white,),
              onPressed: () {
                showModalBottomSheet(context: context, builder: (context) => buildDirectionBottomSheet(context));
              },
            ),
          ],
          centerTitle: true,
          pinned: true,
          expandedHeight: 250.0,
          flexibleSpace: FlexibleSpaceBar(
            background: Stack(
              children: <Widget>[
                Center(
                  child: CircleAvatar(
                    radius: 64.0,
                    child: Image.asset(
                      "assets/pictures/icon.png",
                      width: 100.0,
                      height: 100.0,
                    ),
                    backgroundColor: Colors.white,
                  ),
                ),
                Align(
                  alignment: Alignment(0.0, -0.67),
                  child: Text("باھار كۆپ تىللىق تور لۇغىتى", style: TextStyle(fontFamily: "ukij-title", fontSize: 20.0, color: Colors.white),),
                )
              ],
            ),
            title: makeSearchbar(),
            centerTitle: true,
          ),
        ),
        SliverList(delegate: SliverChildListDelegate(widgetList))
      ],
    );
  }

  Widget makeSearchbar() {
    return Container(
      width: 160.0,
//      color: Colors.green,
      child: TextField(
        style: TextStyle(fontFamily: "ukij", fontSize: 12.0),
        decoration: InputDecoration(
          filled: true,
          fillColor: Colors.white30,
          contentPadding: EdgeInsets.symmetric(vertical: 5.0),
          enabledBorder: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(8.0)),
            borderSide: BorderSide(color: Colors.white30),
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(8.0)),
            borderSide: BorderSide(color: Colors.white30),
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.all(Radius.circular(8.0)),
            borderSide: BorderSide(color: Colors.white30),
          ),
          hintText: "ئىزدىمەكچى بولغان سۆزنى كىرگۈزۈڭ",
          hintStyle: TextStyle(
            color: Colors.white30,
            fontSize: 11.0,
          ),
        ),
        controller: searchController,
        textAlign: TextAlign.center,
      ),
    );
  }

  Widget buildItem(BuildContext context, DictItem data) {
    return ListTile(
      title: Text(data.key),
      subtitle: Text(data.value),
      leading: Image.asset("assets/pictures/agenda.png", width: 30.0, height: 30.0,),
      trailing: Wrap(
        children: <Widget>[
          IconButton(icon: Icon(Icons.favorite), onPressed: (){
            showMessageDialog(context, title: "Information", content: "This feature currently not implemented!");
          })
        ],
      ),
    );
  }

  Widget buildDirectionBottomSheet(BuildContext context){
    return BottomSheet(
      enableDrag: false,
    onClosing: (){

    },
      builder: (context) => Container(
        height: 100.0,
        child: ListView(
          scrollDirection: Axis.horizontal,
          children: directions.map((item) => Container(
            width: 100.0,
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(
                  color: Colors.blue,
                  style: BorderStyle.solid,
                  width: item.code == selectedDirection.code ? 3.0 : 0.0
                )
              )
            ),
//            color: Colors.red,
            margin: EdgeInsets.all(10.0),
            child: GestureDetector(
              onTap: (){
                globalBus.publish(ON_DIRECTION_SELECTED, item);
                Navigator.of(context).pop();
              },
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  Image.asset("assets/pictures/translate.png", height: 50.0, width: 50.0,),
                  Text(item.source + " -- " + item.destination, style: TextStyle(fontSize: 10.0),)
                ],
              ),
            ),
          )).toList()
        ),
      )
    );
  }

  Widget buildSearchModeBottomSheet(BuildContext context){
    return BottomSheet(
        onClosing: (){

        },
        builder: (context) => Container(
          height: 50.0,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
              children: [SearchMode.startswith, SearchMode.contains, SearchMode.endswith].map((item) => GestureDetector(
                onTap: (){
                  globalBus.publish(ON_SEARCH_MODE_SELECTED, item);
                  Navigator.of(context).pop();
                },
                child: Container(
                width: 80.0,
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                            color: Colors.blue,
                            style: BorderStyle.solid,
                            width: item == selectedSearchMode ? 3.0 : 0.0
                        )
                    )
                ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(searchModeStrings[item], style: TextStyle(fontSize: 12.0),)
                    ],
                  ),
                ),
              )).toList()
          ),
        )
    );
  }
}





var searchModeStrings = {
  SearchMode.startswith: "بىشىدىن ئىزدەش",
  SearchMode.contains: "ئىچىدىن ئىزدەش",
  SearchMode.endswith: "ئاخىرىدىن ئىزدەش",
};

